# Prepare Data fron GLES 

# Required package:
library(foreign)
library(dummies)

# Load Data
update.packages("foreign")
gles.raw <- read.dta("gles.dta",convert.factors=FALSE)


# Get variables

rp.ma <- matrix(c(
              "k11","lrcoal_",
              "k1[a-z]","ratcoal_",
              "k15","wahlvig_",
              "a11","wahl_",    
              "a12","rat_",
              "a32","lr_",
              "a33","lrs",
              "a01","info",
              "^a36$","pid",
              "v_01","con_gender",
              "v_03","con_educ",
              "a39a","con_union",
              "a47","con_income",
              "v_02","con_age",
              "^a42$","con_relig"),
                ncol=2,byrow=TRUE
              )


# Second part of name
gles.names <- NULL
for(k in 1:nrow(rp.ma)){  
  gles.names <-   c(gles.names,grep(rp.ma[k,1],names(gles.raw)))
  }
gles <- gles.raw[,gles.names]

# Loop over names and entries in rp.ma gsub
for(i in 1:length(names(gles))){
  for(j in 1:nrow(rp.ma)){
  names(gles)[i] <- gsub(rp.ma[j,1],rp.ma[j,2],names(gles)[i])
  }}


# Comment: Didn't manag to get the coalition rating labels correct. Hand coding:
names(gles)[grep("ratcoal",names(gles))] <- paste("ratcoal_", letters[1:length(grep("ratcoal",names(gles)))],sep=""  )

# Recode
###################

gles[,grep("rat",names(gles))][gles[,grep("rat",names(gles))]>11] <- NA
gles[,grep("lr",names(gles))][gles[,grep("lr",names(gles))]>11] <- NA
gles[,grep("wahl",names(gles))][gles[,grep("wahl",names(gles))]==99] <- NA
gles$pid[gles$pid==99] <- NA
gles$con_income[gles$income==99] <- NA
gles$con_relig <- ifelse(gles$con_relig==1,1,0)

# save
###############

save(gles,file="gles.Rdata")
